import { createRouter, createWebHistory } from 'vue-router'
import menuRoutes from './menu'
import ApiTree from '@/server/api-tree';
import { ElMessage } from 'element-plus';
import { AFTER_SALE_VIEW_Routes } from "./views/after-sale"
import { SHIPPING_VIEW_Routes } from "./views/shipping"
import StoreManager from '@/plugins/storage';


const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_APP_BASE_URL),
  routes: [
    {
      name: "Login",
      path: "/login",
      component: () => import("@/views/user/LoginView.vue")
    },
    {
      name: "Home",
      path: "/",
      component: () => import("@/views/HomeView.vue"),
      children: menuRoutes
    },
    {
      name: "NoAuth",
      path: "/no-auth",
      component: () => import("@/views/NoAuth.vue"),
    },
    {
      name: "CustomerSearch",
      path: "/SelfService",
      component: () => import("@/views/after_sale/order/CustomerSearchView.vue")
    },
    ...AFTER_SALE_VIEW_Routes,
    ...SHIPPING_VIEW_Routes
  ],
})
router.beforeEach((to, from, next) => {
  if (to.name === "Login" || to.name === "CustomerSearch") {
    next();
    return;
  };
  const token = StoreManager.getString("access-token");
  if (!token) {
    router.push({ path: "/login" })
    return;
  }
  const menuCode = to.name?.toString() || "";
  if (menuCode) {
    if (menuCode === "NoAuth") return next();
    ApiTree.auth.checkMenuAuth(menuCode).then(({ success, data: hasPermission }) => {
      if (success) {
        if (hasPermission) {
          next();
        } else {
          ElMessage.error("页面无访问权限，请联系管理员开通");
          router.push({ path: "/no-auth", replace: true })
          return;
        }
      }
    }).catch();
  }
})
export default router
